<template>
  <div class="user_home">
    <div class="user_left">
      <el-input
          placeholder="请输入部门名称"
          prefix-icon="el-icon-search"
          v-model="searchDeptName"
          @input="filterDeptList"
      ></el-input>
      <el-tree
          :data="filteredDeptList"
          :props="defaultProps"
          node-key="id"
          :expand-on-click-node="false"
          :indent="20"
          default-expand-all
          @node-click="handleNodeClick"
      >
      </el-tree>
    </div>
    <div class="user_right">
      <div class="user_right_top">
        <el-form :model="form" :rules="rules" ref="form" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="用户名称" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入用户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" prop="phoneNumber">
                <el-input v-model="form.phoneNumber" placeholder="请输入手机号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="用户状态">
                  <el-option label="正常" value="value1"></el-option>
                  <el-option label="停用" value="value2"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker
                    v-model="form.createTime"
                    type="daterange"
                    range-separator=" - "
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-button icon="el-icon-refresh"  @click="reset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-button type="primary" icon="el-icon-plus" @click="openDialog()">新增</el-button>
            <el-button type="success" icon="el-icon-edit"  @click="openDialog(row)" >修改</el-button>
            <el-button type="danger" icon="el-icon-delete" >删除</el-button>
            <el-button type="info" icon="el-icon-upload2" @click="openImportDialog">导入</el-button>
            <el-button type="warning" icon="el-icon-download" @click="exportTableToExcel">导出</el-button>
          </el-row>
        </el-form>
      </div>
      <div class="user_right_bottom">
        <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading" element-loading-text="数据加载中...">
          <el-table-column prop="userId" label="用户ID" width="80" align="center" />
          <el-table-column prop="userName" width="110px" label="用户名称"  align="center"/>
          <el-table-column prop="nickName" width="110px" label="用户昵称"  align="center"/>
          <el-table-column prop="deptName" width="100px" label="部门"  align="center"/>
          <el-table-column prop="phonenumber" width="120px" label="手机号码"  align="center"/>
          <el-table-column prop="status" width="100px" label="状态"  align="center">
            <el-switch
                v-model="value"
                active-color="#13ce66"
                inactive-color="#ff4949">

            </el-switch>
          </el-table-column>
          <el-table-column prop="createTime" width="165px" label="创建时间"  />

          <el-table-column label="操作"  align="center">
            <template #default="{row}">
              <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="openDialog(row)"
              >编辑</el-button>
              <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--弹框-->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="700px"
    >
      <el-form :model="formData" :rules="rulest" ref="formRef" label-width="100px">
        <!-- 用户昵称和归属部门 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位编码" prop="postCode">
              <el-input v-model="formData.postCode" placeholder="请输入岗位编码"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入用户昵称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptName">
              <el-select v-model="formData.deptName" placeholder="请选择归属部门">
                <el-option v-for="dept in depts" :key="dept.id" :label="dept.label" :value="dept.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 手机号码和邮箱 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="formData.phonenumber" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 用户名称和用户密码 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="formData.userName" placeholder="请输入用户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入用户密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 用户性别 -->
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 岗位和角色 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postName">
              <el-select v-model="formData.postName" placeholder="请选择岗位">
                <el-option v-for="post in posts" :key="post.value" :label="post.label" :value="post.value"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleName">
              <el-select v-model="formData.roleName" placeholder="请选择角色">
                <el-option v-for="role in roles" :key="role.value" :label="role.label" :value="role.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
    <!--  分页-->
    <el-pagination
        class="pagination-wrapper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    />
<!--     用户导入弹框-->
    <el-dialog
        title="用户导入"
        :visible.sync="importDialogVisible"
        width="500px"
    >
      <el-upload
          ref="upload"
          :http-request="handleFileUpload"
          :show-file-list="false"
          accept=".xls,.xlsx"
          drag
          action="https://placeholder.url"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<span>点击上传</span></div>
        <div class="el-upload__tip">仅允许导入 .xls, .xlsx 格式文件。</div>
      </el-upload>
      <el-checkbox v-model="updateSupport">是否更新已存在的用户数据</el-checkbox>
      <a href="/template.xlsx" download>下载模板</a>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpload">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserFn, listUserFn, addAxiofFunInf, editPutFn, deletePostFn, getUsersInfo, exportUserchannel } from "@/api/userfn"; // 添加 getUsersInfo 和 exportUserchannel
import * as XLSX from 'xlsx'; //引入 xlsx 进行导出数据
export default {
  name: "HelloVue",
  data() {
    return {
      value: true,
      loading: false,
      tableData: [],
      dialogVisible: false,
      dialogTitle: '',
      posts: [], // 存储岗位数据
      roles: [], // 存储角色数据
      depts: [], // 存储部门数据

      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 5
      },
      total: 0, // 总记录数

      // 弹框
      formData: {
        postId: null,
        postCode:"",
        nickName: "",
        deptName: "",
        phonenumber: "",
        email: "",
        userName: "",
        password: "",
        postName: "",
        roleName: "",
        sex: "",
        status: "",
        remark: ""
      },
      // 弹框必填验证
      rulest: {
        nickName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
        deptName: [{ required: true, message: "请选择归属部门", trigger: "change" }],
        userName: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
        password: [{ required: true, message: "请输入用户密码", trigger: "blur" }]
      },
      form: {
        userName: "",
        phoneNumber: "",
        status: "",
        createTime: [],
      },

      defaultProps: {
        children: 'children',
        label: 'label' // 使用 label 字段
      },
      rules: {
        userName: [
          { required: false, message: "请输入用户名称", trigger: "blur" },
        ],
        phoneNumber: [
          { required: false, message: "请输入手机号码", trigger: "blur" },
        ],
      },
      deptList: [], // 新增用于存储部门数据的数组
      users: [], // 存储用户数据的数组
      searchDeptName: '', // 用于存储输入框的值
      filteredDeptList: [], // 用于存储过滤后的部门数据
      importDialogVisible: false,
      selectedFile: null,
      updateSupport: false // 是否更新已存在的用户数据
    };
  },
  methods: {

    async openDialog(row = null) {
      this.dialogVisible = true;
      if (row) {
        this.dialogTitle = '修改用户';
        this.formData = {
          ...this.formData,
          postId: row.userId || row.postId, // 确保这里正确赋值
          postCode: row.postCode,
          postName: row.postName,
          roleName: row.roleName,
          nickName: row.nickName,
          deptName: row.deptId,
          phonenumber: row.phonenumber,
          email: row.email,
          userName: row.userName,
          password: row.password,
          sex: row.sex,
          status: row.status,
          remark: row.remark
        };
        try {
          const res = await getUsersInfo({ id: row.userId }); // 根据实际需求传递参数

          if (res.data.code === 200) {
            // 确保 posts 和 roles 的数据格式正确
            this.posts = res.data.posts.map(post => ({ label: post.postName, value: post.postId }));
            this.roles = res.data.roles.map(role => ({ label: role.roleName, value: role.roleId }));
          } else {
            this.$message.error('获取岗位和角色数据失败');
          }
        } catch (error) {
          console.error('获取岗位和角色数据失败:', error);
          this.$message.error('获取岗位和角色数据失败');
        }
      } else {
        this.dialogTitle = '添加用户';
        this.formData = {
          postId: null,
          postCode:"",
          postName: "",
          roleName: "",
          nickName: "",
          deptName: "",
          phonenumber: "",
          email: "",
          userName: "",
          password: "", // 新增用户时密码为空
          sex: "",
          status: "",
          remark: ""
        };
      }
    },
    // 导出
    exportTableToExcel() {
      try {
        const worksheet = XLSX.utils.json_to_sheet(this.tableData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        XLSX.writeFile(workbook, 'users.xlsx');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请检查数据或导出配置');
      }
    },
    // 删除
    async handleDelete(row) {
      if (!row || !row.userId) {
        this.$message.error('请选择要删除的数据');
        return;
      }

      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(async () => {
            try {
              const response = await deletePostFn([row.userId]); // 将 userId 放入数组中
              const res = response.data;
              if (res.code === 200) {
                this.$message.success('删除成功');
                this.getUsersByDeptId();
              } else {
                this.$message.error('删除失败: ', res.msg);
              }
            } catch (error) {
              console.error('请求失败:', error);
              this.$message.error('请求失败: ', error.message);
            }
          });
    },
    // 分页
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getUsersByDeptId(); // 调用获取用户数据的方法
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getUsersByDeptId(); // 调用获取用户数据的方法
    },


    // 搜索
    search() {
      const params = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        userName: this.form.userName,
        phoneNumber: this.form.phoneNumber,
        status: this.form.status,
        createTime: this.form.createTime // 如果 createTime 是一个日期范围，可能需要进一步处理
      };
      this.getUsersByDeptId(null, params);
    },
    // 重置
    reset() {
      console.log('Resetting form...');
      this.$refs.form.resetFields();
      console.log('Form reset:', this.form);
      console.log('Restoring table data...');
      this.getUsersByDeptId(); // 调用 getUsersByDeptId 方法以恢复初始数据
    },


    handleNodeClick(data) {
      if (data.id) {
        this.getUsersByDeptId(data.id);
      } else {
        this.tableData = this.users; // 如果点击的是根节点，显示所有用户
      }
    },

    // 表格
    async getUsersByDeptId(deptId = null, searchParams = {}) {
      try {
        this.loading = true;
        const params = {
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
          deptId: deptId,
          ...searchParams
        };
        const res = await listUserFn(params);
        if (res.data.code === 200) {
          this.allUsers = res.data.rows;
          this.total = res.data.total;
          this.users = res.data.rows.map(user => {
            return {
              ...user,
              deptName: user.dept ? user.dept.deptName : ''
            };
          });
          this.tableData = this.users;
        } else {
          console.error('获取数据失败，响应码:', res.data.code);
        }
      } catch (error) {
        console.error('获取用户数据失败', error);
      } finally {
        this.loading = false;
      }
    },

    async getDeptData() {
      try {
        const res = await getUserFn(); // 修改为 getUserFn

        if (res.data.code === 200) {
          this.deptList = res.data.data;
          this.filteredDeptList = this.deptList; // 初始化部门数据
          this.depts = this.flattenDeptList(this.deptList);
          // 初始化时获取所有用户数据
          await this.getUsersByDeptId(null);
        } else {
          console.error('获取部门数据失败，响应码:', res.data.code);
        }
      } catch (error) {
        console.error('获取部门数据失败', error);
      }
    },
    //确定
    async handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const payload = {
              userId: this.formData.postId, // 确保包含 userId
              deptId: this.formData.deptName || null,
              userName: this.formData.userName,
              nickName: this.formData.nickName,
              password: this.formData.password,
              sex: this.formData.sex || null,
              status: this.formData.status || null,
              postIds: this.formData.postName ? [this.formData.postName] : [],
              roleIds: this.formData.roleName ? [this.formData.roleName] : [],
              remark: this.formData.remark || null
            };

            if (this.formData.postId) {
              await editPutFn(payload);
              this.$message.success('编辑成功');
            } else {
              const response = await addAxiofFunInf(payload);
              console.log('添加成功返回的数据:', response.data);
              this.$message.success('新增成功');
            }
            this.dialogVisible = false;
            this.getUsersByDeptId(); // 刷新用户列表
          } catch (error) {
            console.error('操作失败:', error);
            this.$message.error('操作失败，请检查输入数据');
          }
        }
      });
    },

    async getPostsAndRoles() {
      try {
        const res = await getUsersInfo();
        if (res.data.code === 200) {
          // 确保 posts 和 roles 的数据格式正确
          this.posts = res.data.posts.map(post => ({ label: post.postName, value: post.postId }));
          this.roles = res.data.roles.map(role => ({ label: role.roleName, value: role.roleId }));
        } else {
          this.$message.error('获取岗位和角色数据失败');
        }
      } catch (error) {
        console.error('获取岗位和角色数据失败:', error);
        this.$message.error('获取岗位和角色数据失败');
      }
    },

    filterDeptList() {
      if (this.searchDeptName) {
        const filter = (data, keyword) => {
          return data.filter(node => {
            if (node.label.toLowerCase().includes(keyword.toLowerCase())) {
              return true;
            }
            if (node.children) {
              node.children = filter(node.children, keyword);
              return node.children.length > 0;
            }
            return false;
          });
        };
        this.filteredDeptList = filter(JSON.parse(JSON.stringify(this.deptList)), this.searchDeptName);
      } else {
        this.filteredDeptList = this.deptList;
      }
    },

    flattenDeptList(deptList) {
      let result = [];
      deptList.forEach(dept => {
        result.push({ id: dept.id, label: dept.label });
        if (dept.children) {
          result = result.concat(this.flattenDeptList(dept.children));
        }
      });
      return result;
    },
    openImportDialog() {
      this.importDialogVisible = true;
    },
    handleFileUpload(file) {
      this.selectedFile = file.file;
    },
    async confirmUpload() {
      if (!this.selectedFile) {
        this.$message.error("请先选择文件");
        return;
      }
      const formData = new FormData();
      formData.append("file", this.selectedFile);
      formData.append("updateSupport", this.updateSupport ? 1 : 0);
      try {
        const response = await exportUserchannel(formData);
        if (response.code === 200) {
          this.$message.success("文件上传成功");
          this.importDialogVisible = false;
          this.getUsersByDeptId(); // 刷新用户列表
        } else {
          this.$message.error(response.msg || "文件上传失败");
        }
      } catch (error) {
        console.error("文件上传失败:", error);
        this.$message.error("文件上传失败，请重试");
      }
    }
  },
  created() {
    this.getUsersByDeptId();
    this.getDeptData();
    this.getPostsAndRoles(); // 初始化岗位和角色数据
  }
};

</script>

<style scoped>
.user_home {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
}
.user_left {
  width: 21%;
  float: left;
  padding: 5px;

}
.user_right {
  width: 79%;
  float: left;
}
.user_right_top {
  width: 100%;
  height: auto;
  padding: 5px;
}
.pagination-wrapper {
  position: absolute;
  bottom: 0;
  right: 20px;
}
</style>
